package com.mooral.web.action.voucher;

import java.sql.ResultSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.mooral.bean.Voucher;
import com.mooral.bean.Vouchers;
import com.mooral.context.Context;
import com.mooral.dataAccess.DataAccessConnection;
import com.mooral.web.action.MooralAction;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;


public class SearchAction extends MooralAction {

	@Override
	public ActionForward perform(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			Context context) throws Exception {

		DynaActionForm dform = (DynaActionForm) form;
		String query = ((String)dform.get("query")).trim();
		log.debug("[" + context.getSessionId() + "] - " + "Query: " + query);
		

		int pageSelected = 1;
		if(request.getParameter("pageSelected")!= null){
			try {
				pageSelected = Integer.parseInt( request.getParameter("pageSelected") );
			} catch(NumberFormatException e) {
				pageSelected = new Integer(1);
			}
		}
			
		
		
		Vouchers vouchers = new Vouchers();
		
		String sql = "";
		if (query.trim().length() < 5) {
			sql = "select * from vouchers where title like '%" + query + "%' limit " + (pageSelected - 1) * Context.PAGE_SIZE + "," +Context.PAGE_SIZE;
		} else {
			sql = "select 		v.*," +
			"  					MATCH(v.description) AGAINST('+" + query + "') AS score" +
			"  		from 		vouchers v" +
			"		where 		MATCH(description) AGAINST ('+" + query + "' IN BOOLEAN MODE)" +
			"		limit 		" + (pageSelected - 1) * Context.PAGE_SIZE + ", " + Context.PAGE_SIZE;
		}

		
		request.setAttribute("headerTitle", "Searching for: " + query);
		
		vouchers.populate(sql);
		request.setAttribute("vouchers", vouchers);
		
		// Paginacion
		//request.setAttribute("listSize", new Integer(listSize));
		request.setAttribute("listSize", vouchers.getCount(sql));
		request.setAttribute("actionSearch", mapping.getPath());
		request.setAttribute("query", query);
		request.setAttribute("pageSelected", new Integer(pageSelected));

		
		//System.out.println( "----------------" + org.apache.struts.util.MessageResources.getMessageResources("MessageResources").getMessage("voucher.search.label.search") );
		
		return mapping.findForward(ACTION_SUCCESS);
	}

}
